package com.tungse.redis_test.controller;

import lombok.val;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.*;
import org.springframework.web.bind.annotation.*;

import javax.print.DocFlavor;
import java.util.List;
import java.util.Map;
import java.util.Set;

@RestController
@RequestMapping("dt")
public class RedisDataTypeHandler {


    @Autowired
    private RedisTemplate redisTemplate;


    @GetMapping("/string/{key}/{val}")
    public String stringTest(@PathVariable String key, @PathVariable String val) {
        redisTemplate.opsForValue().set(key, val);
        String str = (String) redisTemplate.opsForValue().get(key);
        return str;
    }

    @PostMapping("/list/{key}")
    public List<String> listTest(@PathVariable String key, @RequestBody List<String> list){

        ListOperations<String, String> listOperations = redisTemplate.opsForList();
        //单个写入
        listOperations.leftPush(key, "a");
        //批量写入
        listOperations.leftPushAll(key, list);

        //获取列表//end 为-1 表示获取所有
        return listOperations.range(key, 0, -1);
    }

    @PostMapping("/set/{key}")
    public Set<String> setTest(@PathVariable String key, @RequestBody List<String> list){
        SetOperations<String, String> setOperations = redisTemplate.opsForSet();
        //setOperations.add(key, list.toArray(new String[list.size()]));
        for (String s : list) {
            setOperations.add(key, s);
        }

        return setOperations.members(key);
    }

    @PostMapping("/zset/{key}")
    public Set<String> zsetTest(@PathVariable String key, @RequestBody List<String> list){
        ZSetOperations<String, String> zSetOperations = redisTemplate.opsForZSet();
        for (int i=0; i<list.size(); i++) {
            zSetOperations.add(key, list.get(i), i);
        }
        //获取集合//end 为-1 表示获取所有
        return zSetOperations.range(key, 0, -1);
    }

    @PostMapping("/hash/{key}")
    public Map<String, String> hashTest(@PathVariable String key, @RequestBody Map<String, String> map){
        HashOperations<String, String, String> hashOperations = redisTemplate.opsForHash();
        //单个写入
        for (String s : map.keySet()) {
            hashOperations.put(key, s, map.get(s));
        }
        //批量写入
        //hashOperations.putAll(key, map);
        //获取指定hash key的值
        // String name = hashOperations.get(key, "name");
        //获取所有key
        return hashOperations.entries(key);
    }

    @GetMapping("/test/type/{value}")
    public void testType(@PathVariable Long value){

        redisTemplate.opsForValue().set("value", value);

        System.out.println(redisTemplate.opsForValue().get("value"));

        Long o = (Long) redisTemplate.opsForValue().get("value");

        System.out.println(o);
    }

}

